/*-----------------------------
----$Source: Volumes://MATEOR/vais/modules/braindo/braindo.c$
----$Date: June 30, 2012$
-------------------------------
VAIS Copyright Matthew Caswell, 2012
-----------------------------*/
#include<stdio.h>
#include<stdlib.h>
#include<braindo.h>
#include<lstring.h>
#include<vais.h>
#include<string.h>
#include<lds_ts.h>

void initFunction (VAIS_Func_t* DS, char* DS_Record){
  FILE* DS_FILE;
  
  debug ("initFunction", "initFunction", "braindo/braindo.c");
  
  char c[DS_MD];
  int n = 0;
  
  if((DS_FILE = fopen (DS_Record, "r"))){
  
    while(!(feof (DS_FILE))){
      c[n] = (char)fgetc (DS_FILE);
      (*DS).dataStream[n] = c[n];
      debug_c (c[n], "initFunction", "braindo/braindo.c");
      n++;
    }
  
    fclose (DS_FILE);
    
  }else{
    DS_FILE = fopen ("VAIS.memory/VAIS.empty.function", "r");

    while(!(feof (DS_FILE))){
      c[n] = (char)fgetc (DS_FILE);
      (*DS).dataStream[n] = c[n];
      debug_c (c[n], "initFunction", "braindo/braindo.c");
      n++;
    }
  
    fclose (DS_FILE);
    
  }
}

void sortFunction (char str[DS_MD], char* c[DS_MD], VAIS_Func_t* DS){
  int n = 0;
  
  c[n] = strtok (str, " ");
  debug (c[n], "sortFunction", "braindo/braindo.c");
  n++;
  while ((c[n] = strtok (null, " "))){
    debug (c[n], "sortFunction", "braindo/braindo.c");
    n++;
  }
  
  (*DS).index = n;
}

void parseFunction (VAIS_Func_t* DS){
  int hi;
  sscanf ((*DS).dataSeg[0], "%7c%17i", (*DS).first[0], &hi);
  debug ("%7c%17d", "parseFunction", "braindo/braindo.c");
  char buffer[DS_MD];
  int a;
  a = sprintf (buffer, "%%%ic%%5c", hi);
  sscanf ((*DS).dataSeg[1], buffer, (*DS).first[1], (*DS).second[1]);
  debug (buffer, "parseFunction", "braindo/braindo.c");
}

void h_Function (VAIS_Func_t* DS, char* DS_Record){
  initFunction (DS, DS_Record);
  sortFunction ((*DS).dataStream, (*DS).dataSeg, DS);
  debug ("sorted", "h_Function", "braindo/braindo.h");
  int n = 0;
  parseFunction (DS);
  debug ("parsed", "h_Function", "braindo/braindo.h");
  for(; n<(*DS).index; n++){
    debug ((*DS).first[n], "h_Function", "braindo/braindo.c");
    debug ((*DS).second[n], "h_Function", "braindo/braindo.c");
  }
  
}

void VAIS_braindo (char* DS_Record, int run){
  
  VAIS_Func_t* DS = malloc (sizeof (*DS));
  h_Function (DS, DS_Record);
  
  int i = 0;
  int n;
  
  for(; i<(*DS).index && n != -1; i++){
    if(strcmp((*DS).first[i], "0x0BEBE") == 0){
      printf ("{-- VAIS Says: %s --}\n", (*DS).first[i + 1]);
      if(run > 5){
        printf ("{-- BrainDo: Communication functions: %s : \e[1;31mNEURAL SIEZURE!!!\e[0m --}\n", (*DS).first[i]);
      }
      run++;
      n = -1;
    }else if(strcmp((*DS).first[i], "0x00000") == 0){
      debug ((*DS).first[i], "(null) function", "BrainDo");
    }else{
      debug ((*DS).first[i], "Unknown command", "BrainDo");
    }
  }
  // ...
}